import React, { Component } from 'react';
import { Col, Form, Modal, Row } from 'antd';

const FormItem = Form.Item;

class EditForm extends Component {
  handleOk = () => {
    const { form, onOk } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      onOk(fieldsValue);
    });
  };

  render() {
    const { rows, form, optFlag, visible, onCancel, confirmLoading, title } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Modal
        maskClosable={false}
        destroyOnClose
        title={title}
        visible={visible}
        okText="确定"
        cancelText="取消"
        onOk={this.handleOk}
        onCancel={onCancel}
        confirmLoading={confirmLoading}
      >
        <Form>
          <Row gutter={{ md: 1, lg: 2, xl: 4 }}>
            {rows.map(row => {
              return row.cols.map((col, i) => {
                return (
                  <Col md={col.md} sm={24}>
                    <FormItem key={i} label={col.label}>
                      {getFieldDecorator(col.name, { rules: col.rules })(col.component)}
                    </FormItem>
                  </Col>
                );
              });
            })}
          </Row>
        </Form>
      </Modal>
    );
  }
}

EditForm = Form.create({
  onFieldsChange(props, changedFields) {
    props.onFieldsChange(changedFields);
  },
  mapPropsToFields(props) {
    const { fieldValue, rows } = props;
    let fields = {};
    rows.map(row => {
      row.cols.map(col => {
        fields[col.name] = Form.createFormField({
          ...fieldValue[col.name],
        });
      });
    });
    return fields;
  },
})(EditForm);

export default EditForm;
